<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: ../unilogin/index.html");
    exit();
}

include 'db_connect.php';

if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit();
}

$post_id = $_GET['id'];

// 获取帖子原作者信息
$sql = "SELECT author FROM posts WHERE id = $post_id";
$result = $conn->query($sql);

if ($result->num_rows == 0) {
    header("Location: index.php");
    exit();
}

$post = $result->fetch_assoc();

// 验证权限
if ($_SESSION['username'] != $post["author"]) {
    die("您没有权限删除这篇文章！");
}

// 先删除关联评论
$conn->query("DELETE FROM comments WHERE post_id = $post_id");

// 再删除帖子
$sql = "DELETE FROM posts WHERE id = $post_id";
if ($conn->query($sql) === TRUE) {
    header("Location: index.php?deleted=1");
} else {
    echo "删除失败: " . $conn->error;
}

$conn->close();
?>
